package com.medishare.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.medishare.R;
import com.medishare.activity.ActivityCallCenter;
import com.medishare.activity.ActivityTestQuestions;
import com.medishare.activity.MainActivity;
import com.medishare.adapter.AdapterCallAssistant;
import com.medishare.data.DataMember;
import com.medishare.util.Utils;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentHealthTest extends Fragment implements OnClickListener{

	private Activity mainActivity;
	private RelativeLayout rl1;
	private RelativeLayout rl2;
	private GridView mGridView;
    public final static String  TAG = FragmentHealthTest.class.getSimpleName();
    public final static boolean DEBUG = true;
    private String selectedId = "";
	private Button mBtnIntro;
	private Button mBtnQuiz;
	private DialogFragment dialog;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_health_test, null);
		rl1 = (RelativeLayout) view.findViewById(R.id.rl1);
		rl2 = (RelativeLayout) view.findViewById(R.id.rl2);
		mGridView = (GridView) view.findViewById(R.id.gridview_memeber);
		mBtnIntro = (Button) view.findViewById(R.id.btn_intro);
		mBtnQuiz = (Button) view.findViewById(R.id.btn_quiz);
		mBtnIntro.setOnClickListener(this);
		mBtnQuiz.setOnClickListener(this);
		String url = Utils.getBaseUrl() + "Member/read/?uuid=" + Utils.getDeviceUUID(mainActivity);
		if(DEBUG){
			Log.i(TAG,url);
		}
		loadData(url);
		return view;
	}

	private void loadData(String url){
		AsyncHttpClient client = new AsyncHttpClient();
		final ArrayList<DataMember> datas = new ArrayList<DataMember>(); 
		client.get(url, new AsyncHttpResponseHandler(){

			@Override
			public void onSuccess(String content)  {
				super.onSuccess(content);
				if(DEBUG){
					Log.i(TAG,content);
				}
				Message msg = new Message();
				try {
					
					JSONObject jsonObject = new JSONObject(content);
					int status = jsonObject.getInt("status");
					if(status == 0){
						msg.what = 1;
						mHandler.sendMessage(msg);
						return;
					}
					JSONObject jsonData = jsonObject.getJSONObject("data");
					JSONArray jsonArray = jsonData.getJSONArray("member");
					for(int i=0;i<jsonArray.length();i++){
						JSONObject tempObject = (JSONObject) jsonArray.get(i);
						DataMember member = new DataMember();
						member.setId(tempObject.getString("id"));
						member.setName(tempObject.getString("name"));
						member.setGender(tempObject.getString("gender"));
						member.setRelation(tempObject.getString("relation"));
						member.setBirthday(tempObject.getString("birthday"));
						member.setFamily_id(tempObject.getString("family_id"));
						member.setIdno(tempObject.getString("idno"));
						member.setHis_id(tempObject.getString("his_id"));
						member.setMobile(tempObject.getString("mobile"));
						member.setEmail(tempObject.getString("email"));
						member.setStatus(tempObject.getString("status"));
						member.setRemark(tempObject.getString("remark"));
						member.setCreate_time(tempObject.getString("create_time"));
						member.setUpdate_time(tempObject.getString("update_time"));
						datas.add(member);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				msg.what = 0;
				msg.obj = datas;
				mHandler.sendMessage(msg);
			}
			
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dialog = ProgressDialogFragment.newInstance();
		dialog.show(getFragmentManager().beginTransaction(), "progress");
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mainActivity =  activity;
		
	}
    
	Handler mHandler = new Handler(){

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (dialog != null && dialog.getDialog().isShowing()) {
				dialog.dismiss();
			}
			switch(msg.what){
			case 0:
				ArrayList<DataMember> datas = (ArrayList<DataMember>) msg.obj;
				final AdapterCallAssistant adapter = new AdapterCallAssistant(mainActivity, datas);
				mGridView.setAdapter(adapter);
				mGridView.setOnItemClickListener(new OnItemClickListener() {

					private View currentSelectedView;

					@Override
					public void onItemClick(AdapterView<?> parent, View v,
							int position, long id) {
						if (currentSelectedView != null && currentSelectedView != v) {
					        unhighlightCurrentRow(currentSelectedView);
					    }
                        
						currentSelectedView = v;
					    highlightCurrentRow(currentSelectedView);
					    
					    DataMember member = (DataMember) mGridView.getAdapter().getItem(position);
					    selectedId = member.getId();
					    
					}
				});
				rl1.setVisibility(View.VISIBLE);
				rl2.setVisibility(View.GONE);
				break;
			case 1:
				rl1.setVisibility(View.GONE);
				rl2.setVisibility(View.VISIBLE);
				break;
			}
		}
    	
    };
	
    private void unhighlightCurrentRow(View rowView) {
    	rowView.setBackgroundResource(R.drawable.bg_default_textview);
    	((TextView)rowView).setTextColor(Color.BLACK);
    }

    private void highlightCurrentRow(View rowView) {
        rowView.setBackgroundResource(R.drawable.bg_selected_textview);
        ((TextView)rowView).setTextColor(Color.WHITE);
    }

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.btn_intro:
			
			break;

		case R.id.btn_quiz:
			if(selectedId.equals("")){
				Toast.makeText(mainActivity, "请先选择家庭成员", 1).show();
				return;
			}
		    Intent i = new Intent(mainActivity,ActivityTestQuestions.class);
		    i.putExtra("selectedId", selectedId);
		    mainActivity.startActivity(i);
			break;
		
		case R.id.btn_call_list:
			break;
			
		default:
			break;
		}
	}
    
    
}
